/*
# ------------------------------------------------------------------------
# JD Base Theme
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
 */
//Need to init jquery ui tabs and pull general configuration to general tabs
var t3_form;

var t3_form_elements = {};

var t3_profile_elements = {};
var t3_current_profile;
var t3_current_layout;

var t3_layout_current_task = '';
// for submit t3 ajax before submit main form to drupal
var t3_save = false;

var t3_default_vals = new Array();

function t3_init() {
	t3_form = jQuery('#system-theme-settings');
	t3_init_default();
	t3_init_tabs();

	t3_init_tooltip();

	t3_general_init();
	// profile init function
	t3_profile_init();

	// layout init function
	t3_layout_init();

	// themes init function
	t3_init_upload_theme();

	// get submit button
	var theme_submit_btn = jQuery('#edit-submit');

	theme_submit_btn.click(function() {
		t3_store();
		return false;
	});
}

function t3_init_default() {
	t3_default_vals['profile'] = new Array();
	t3_default_vals['profile']['setting_font'] = 3;
	t3_default_vals['profile']['setting_screen'] = 'wide';
	t3_default_vals['profile']['setting_specialwidth'] = '';
	t3_default_vals['profile']['setting_t3_logo'] = 't3-logo t3-logo-light';
	var elements = [ 'global', 'logo', 'slogan', 'blocktitle', 'pageheading',
			'nodeheading', 'mainnav' ];

	for (i = 0; i < elements.length; i++) {
		t3_default_vals['profile']['gfont_' + elements[i]] = '0';
		t3_default_vals['profile']['gfont_' + elements[i] + '.style'] = '';
	}

	t3_default_vals['profile']['menu'] = 'primary-links';
	t3_default_vals['profile']['menu_style'] = 'css';
	t3_default_vals['profile']['menu_effectin'] = 'jswing';
	t3_default_vals['profile']['menu_effectout'] = 'jswing';
	t3_default_vals['profile']['menu_durationin'] = '300';
	t3_default_vals['profile']['menu_durationout'] = '400';
	t3_default_vals['profile']['menu_delay'] = '1000';
	t3_default_vals['profile']['themes'] = 'default';
	t3_default_vals['profile']['layout_desktop'] = 'default';
	t3_default_vals['profile']['layout_handheld'] = 'handheld';
	t3_default_vals['profile']['layout_iphone'] = 'iphone';

	t3_default_vals['profile']['option_font'] = '0';
	t3_default_vals['profile']['option_screen'] = '0';
	t3_default_vals['profile']['option_profiles'] = '0';
	t3_default_vals['profile']['option_layouts'] = '0';
	t3_default_vals['profile']['option_menu'] = '0';
}

function t3_init_tooltip() {
	// find form-item first
	var form_items = jQuery('#jd-theme-setting').find('div.form-item');

	form_items.each(function(index, item) {
		var label = jQuery(item).children('label');

		var des = jQuery(item).children('div.description');

		if (jQuery.trim(jQuery(des).text()) != '') {
			if (!jQuery(label).hasClass('option')) {
				var title = jQuery(label).text();
				var title_body = jQuery(des).html();
				var span = jQuery('<span class="tooltip ja-tooltip"></span>');
				span.html(jQuery(label).html());

				jQuery(label).html('');
				span.appendTo(jQuery(label));
				span.attr('title', title + ' - ' + title_body);
				span.tooltip( {
					showBody : ' - ',
					showURL : false
				});

				jQuery(des).remove();
			} else {
				var title = jQuery(label).text();
				var title_body = jQuery(des).html();
				var span = jQuery('<span class="tooltip ja-tooltip"></span>');
				span.html(jQuery(label).html());

				jQuery(label).text('');
				span.appendTo(jQuery(label));
				span.attr('title', title + ' - ' + title_body);
				span.tooltip( {
					showBody : ' - ',
					showURL : false
				});

				jQuery(des).remove();

			}
		}
	});
	$('.gfont-custom').each(function() {
		var span = jQuery('span', this);
		span.tooltip( {
			showBody : ' - ',
			showURL : false
		});
	});
}

function t3_init_tabs() {
	jQuery("#jd-theme-setting > ul > ul.primary").tabs(
			{
				cookie : {
					expires : 356
				},
				show : function(event, ui) {
					var selected_tab = jQuery(ui.tab);
					var name = (selected_tab.text()).toLowerCase();

					var uls = jQuery("#jd-theme-setting  ul.secondary");
					uls.each(function(index, ul) {
						if (selected_tab.attr('href') == '#theme-profiles') {
							var children = jQuery(ul).find(
									'.jd-profile,.jd-new-profile');
							jQuery(children).show();
						} else {
							var children = jQuery(ul).find(
									'.jd-profile,.jd-new-profile');
							jQuery(children).hide();
						}

						var helper = jQuery(ul).children('li.ja-icon-help');
						jQuery(helper).unbind('click');

						jQuery(helper).click(function() {
							t3_show_help(selected_tab.attr('href'));
						});
					})
				}
			});

}
// ////////////////////////////////////////////////////
// ////////////////GENERAL FUNCTION ///////////////////
// ////////////////////////////////////////////////////
function t3_general_init() {
	var t3_general_profile_dialog = jQuery('<div id="t3_general_profile_dialog" class="jd-click-dialog"></div>');
	var html = '';
	html = '<ul>';
	for (name in t3_profiles) {
		html += '<li>' + name + '</li>';
	}
	html += '</ul>';

	t3_general_profile_dialog.html(html);
	t3_general_profile_dialog.prependTo(jQuery('body'));

	t3_general_profile_dialog.hide();
	// pages editor dialog
	var t3_general_page_dialog = jQuery('<div id="t3_general_page_dialog"></div>');

	html = '<textarea id="t3_general_page_editor" name="t3_general_page_editor"></textarea>';

	t3_general_page_dialog.html(html);

	t3_general_page_dialog.dialog( {
		title : Drupal.t('Edit page'),
		width : 300,
		height : 200,
		autoOpen : false
	});

	t3_general_addevent();

	// check if have any change of this mark tab as red
	var inputs = jQuery('#theme-general').find(':input');
	inputs.each(function(i, input) {
		$(input).change(function() {
			t3_tab_change('general');
		});
	});
}

function t3_general_addevent() {
	// open editor dialog
	jQuery('#theme-general  td > span.general-page').unbind('click');

	var dialog = jQuery('#t3_general_page_dialog');

	jQuery('#theme-general td > span.general-page').click(
			function() {
				var jq_span = jQuery(this);
				if (!jQuery(this).hasClass('all')) {
					dialog.dialog('open');
					var value = jq_span.text();

					// reset to null value if it is just indicator
					if (value == Drupal.t('Click to add')) {
						value = '';
					}

					jQuery('#t3_general_page_editor').attr('value',
							jQuery.trim(value.replace(/[,\s]+/g, "\n")));
					dialog.dialog("option", "buttons", {
						"Ok" : function() {
							var page_val = jQuery('#t3_general_page_editor')
									.attr('value');
							var profile = jq_span.parent().next().find('span')
									.text();

							if (jQuery.trim(page_val) == '') {
								if (jq_span.hasClass('page-more')) {
									jQuery(this).dialog("close");
								} else {
									alert(Drupal.t('Pages cannot be empty.'));
								}
							} else {
								page_val = page_val.replace(/[\n\s]+/g, ', ');
								var old_page_val = jQuery.trim(jq_span.text().replace(/[\s]+/g,''));
								jq_span.text(page_val);
								if (jq_span.hasClass('page-more')) {

									var td = jq_span.parent();
									// check if value is empty

									// set property if this is empty tr
									jq_span.removeClass('page-more');
									var tr = jQuery(td).parent();
									jQuery(tr).css('opacity', 1);
								} else {
									delete t3_general[old_page_val];
									t3_general[page_val.replace(/[,]+\s*/g,',')] = profile;
								}
								jQuery(this).dialog("close");
							}
						},
						"Cancel" : function() {
							var page_val = jQuery('#t3_general_page_editor')
									.attr('value');

							jQuery(this).dialog("close");
						}
					});
				}
			});

	// add click event to profile text
	jQuery('.profile-text').unbind('click');
	jQuery('.profile-text').click(function(ev) {
		var td = jQuery(this).parent();
		var btd = jQuery(td).prev();

		var span = btd.find('span');
		if (!jQuery(span).hasClass('page-more')) {
			t3_general_select_profile(this);
			ev.stopPropagation();
		}
	});

	// add close event
	var closes = jQuery('#theme-general').find('span.jd-close');
	jQuery(closes).unbind('click');
	jQuery(closes).click(
			function() {
				var td = jQuery(this).parent();

				var pre_td1 = td.prev();
				var span_td1 = jQuery(pre_td1).find('span');
				var pre_td2 = jQuery(pre_td1).prev();

				var span_td2 = jQuery(pre_td2).find('span');

				if (!jQuery(span_td2).hasClass('page-more')
						&& !jQuery(span_td1).hasClass('more')) {
					var pages = jQuery(span_td2).text();
					delete t3_general[pages];
					var tr = jQuery(td).parent();
					tr.remove();
					t3_tab_change('general');
				}
			});
}
function t3_general_select_profile(span) {
	var dialog = jQuery('#t3_general_profile_dialog');

	var td = jQuery(span).parent();

	var pos = jQuery(td).offset();

	dialog.css('top', pos.top + 20);
	dialog.css('left', pos.left);
	dialog.show();
	var lis = jQuery('#t3_general_profile_dialog').find('li');
	jQuery(lis).unbind('click');

	jQuery(lis)
			.click(
					function() {
						var old_profile = jQuery(span).text();
						var profile = jQuery.trim(jQuery(this).text());
						jQuery(span).text(profile);

						// find page
						td_page = jQuery(td).prev();

						var pages = jQuery(td).prev().find('span').text();
						if (pages == Drupal.t('All pages'))
							pages = 'default';
						jQuery(span).removeClass('more');

						// check if have not empty row, insert it
						var tr = jQuery(td).parent();
						var ntr = jQuery(tr).next();

						if (jQuery(ntr).attr('tagName') == undefined) {
							// need to add more to t3_general
							t3_general[pages] = profile;
							var etr = jQuery('<tr></tr>');
							var html = '';
							html += '<td><span class="general-page page-more">'
									+ Drupal.t('Click to add') + '</span></td>';
							html += '<td><span class="profile-text more">&nbsp;</span></td>';
							html += '<td><span class="jd-close">&nbsp;</span></td>';

							etr.html(html);
							etr.css('opacity', '0.3');
							etr.insertAfter(jQuery(tr));
							t3_general_addevent();
							t3_tab_change('general');
						} else {
							if (old_profile != profile) {
								t3_general[pages] = profile;
								t3_tab_change('general');
							}
						}
					});

}
// ////////////////////////////////////////////////////
// ////////////////PROFILE FUNCTION ///////////////////
// ////////////////////////////////////////////////////
function t3_profile_init() {

	t3_current_profile = 'default';
	// get all child element of profile first
	t3_profile_elements = jQuery('#theme-profiles').find(':input');

	// init profile element change handle
	t3_profile_elements.each(function(index, element) {
		jQuery(element).change(function() {
			t3_profile_element_change(this);
		});
	});

	// init new profile dialog
	var t3_profile_dialog = jQuery('<div id="t3_profile_dialog_new"></div>');
	// add textarea here
	var html = '';
	html += '<span>' + Drupal.t('Name') + ':</span>';
	html += '<input type="textbox" class="t3-admin-profile-new" style="width:300px;" name="t3_profile_name_edit" id="t3_profile_name_edit" />';
	html += '<input type="hidden" name="t3_profile_name_task" id="t3_profile_name_task" value="new" />';
	html += '<input type="hidden" name="t3_profile_name_source" id="t3_profile_name_source" value="" />';

	t3_profile_dialog.html(html);

	t3_profile_dialog.dialog( {
		title : Drupal.t('New profile'),
		width : 400,
		height : 120,
		buttons : {
			"Ok" : function(ev, ui) {
				var profile_task = jQuery('#t3_profile_name_task')
						.attr('value');

				if (profile_task == 'new') {
					t3_profile_ajax_add(ev);
				}

				if (profile_task == 'clone') {
					t3_profile_clone_submit(ev);
				}

				if (profile_task == 'rename') {
					t3_profile_rename_submit(ev);
				}

			},
			"Cancel" : function() {
				jQuery(this).dialog("close");
			}
		},
		autoOpen : false
	});

	// need to init select profile
	var lis = jQuery("#jd-theme-setting  ul.profile > li");

	lis
			.each(function(index, li) {

				// for default span click
				var action = jQuery(li).find('span.jd-profile-action');

				if (action.length) {
					action.click(function(event) {
						t3_profile_action_show(jQuery(li).attr('id'));
						event.stopPropagation();
					});
				}

				// for select each profile click
				if (!jQuery(li).hasClass('jd-new-profile')
						&& !jQuery(li).hasClass('ja-icon-help')) {
					jQuery(li)
							.click(
									function() {
										var alis = jQuery("#jd-theme-setting  ul.profile > li");
										alis.each(function(index, oli) {
											jQuery(oli).removeClass('active');
											var action = jQuery(oli).find(
													'span');

											if (jQuery(action).hasClass(
													'jd-profile-action')) {
												jQuery(action).remove();
											}
										});
										jQuery(this).addClass('active');
										var action = jQuery('<span class="jd-profile-action">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>');
										action.appendTo(jQuery(this));

										action.click(function(event) {
											t3_profile_action_show(jQuery(li)
													.attr('id'));
											event.stopPropagation();
										});
										t3_profile_select(this.id);
										t3_profile_build_suffix_table();
									});
				} else if (jQuery(li).hasClass('jd-new-profile')) {
					jQuery(li).click(
							function() {
								jQuery('#t3_profile_name_task').attr('value',
										'new');
								jQuery('#t3_profile_name_edit').attr('value',
										'');
								jQuery('#t3_profile_name_edit').focus();
								t3_profile_dialog.dialog('option', 'title',
										Drupal.t('New profile'));
								t3_profile_dialog.dialog('open');
							});
				} else if (jQuery(li).hasClass('ja-icon-help')) {

				}

			});

	t3_profile_theme_init();

	// init profile action dialog
	t3_profile_action_init();
	// select default profile when init
	t3_profile_select(t3_current_profile);

}
// Build a table of class suffix configuration
function t3_profile_build_suffix_table() {
	// get data
	var block = t3_profiles[t3_current_profile]['block'];
	// refresh the select
	jQuery('#block_item option').each(function() {
		jQuery(this).attr('disabled', false);
	});
	var html = '';
	if (block) {
		jQuery.each(block, function(id) {
			var name = t3_profile_get_block_name(id);
			html += '<tr id="block-' + id + '">';
			html += '<td class="block-name">' + name + '</td>';
			html += '<td>' + block[id] + '</td>';
			html += '<td><span class="ja-delete" onclick="t3_sblock_delete('
					+ id + ')">' + Drupal.t('Delete') + '</span></td>';
		});
		jQuery('#block-class-suffix-table tbody').html('');
		jQuery('#block-class-suffix-table tbody').html(html);
	}
}
function t3_profile_get_block_name(id) {
	var name = '';
	jQuery('#block_item option').each(function() {
		if (jQuery(this).attr('value') == id) {
			name = jQuery(this).text();
			// Also disable
			jQuery(this).attr('disabled', true);
			return false;
		}
		return true;
	});
	return name;
}
function t3_profile_theme_init() {
	var t3_profile_theme_dialog = jQuery('<div id="t3_profile_theme_dialog" class="jd-click-dialog show-when-click"></div>');

	var nItem = 0;
	var ul = jQuery('<ul id="avail-themes"></ul>');
	// first seach in core themes
	var html = '';
	for (name in t3_themes) {
		nItem++;
		if (name == 'default') {
			html += '<li><input checked="checked" disabled type="checkbox"  value="'
					+ name + '" name="themes[]" />';
		} else {
			html += '<li><input type="checkbox" value="' + name
					+ '" name="themes[]" />';
		}

		html += '<span>' + Drupal.t(name) + '</span></li>';
	}

	ul.html(html);

	ul.appendTo(t3_profile_theme_dialog);

	t3_profile_theme_dialog.prependTo(jQuery('body'));
	jQuery('#t3_profile_theme_dialog').hide();

	jQuery('#jd-edit-sub-theme').click(function(event) {
		if (!jQuery(this).parent().hasClass('disabled')) {
			jQuery('#t3_profile_theme_dialog').css( {
				left : window.mouseXPos + 'px',
				top : window.mouseYPos + 'px'
			});

			jQuery('#t3_profile_theme_dialog').show();
			event.stopPropagation();
		}
	});
	// available theme have action when checked

	var selected_themes = jQuery('#selected-themes');
	var avail_themes = jQuery('#avail-themes');

	var checkboxs = jQuery('ul#avail-themes > li > input');
	checkboxs.each(function(index, checkbox) {
		var li = jQuery(checkbox).parent();
		jQuery(checkbox).change(
				function() {
					// If selected have not checked box, add to it
					if (checkbox.checked) {

						var childs = selected_themes.find('span[id='
								+ checkbox.value + ']');
						if (!childs.length) {
							var addItem = jQuery('<span id="' + li.text()
									+ '" class="jd-sub-theme">' + li.text()
									+ '</span>');
							addItem.appendTo(jQuery('#selected-themes'));
						}
					} else {
						var childs = selected_themes.find('span[id='
								+ checkbox.value + ']');
						jQuery(childs).remove();
					}

					var theme_hidden = t3_form.find('input[name=themes]');
					jQuery(theme_hidden).attr('value',
							jQuery('#selected-themes').sortable('toArray'));

					t3_profile_element_change(theme_hidden);
				});
	})

	// init sortable for selected theme
	jQuery("#selected-themes").sortable(
			{
				placeholder : "jd-sub-theme-space",
				forcePlaceholderSize : true,
				revert : true,

				stop : function() {
					var theme_hidden = t3_form.find('input[name=themes]');
					jQuery(theme_hidden).attr('value',
							jQuery('#selected-themes').sortable('toArray'));

					t3_profile_element_change(theme_hidden);
				}
			}).disableSelection();
}

function t3_profile_action_init() {
	// create action dialog
	var profile_action = jQuery('<div class="jd-profile-action-dialog jd-click-dialog" id="jd-profile-action-dialog">This is content</div>');
	profile_action.prependTo(jQuery('body'));
	profile_action.hide();
}

function t3_profile_action_show(id) {
	id = id.replace(/t3-admin-profile-/, '');
	var profiles = t3_profiles[id];

	var ul = jQuery('<ul></ul>');
	var li_clone = jQuery('<li class="saveas" onclick="t3_profile_clone(\''
			+ id + '\')">' + Drupal.t("Clone") + '</li>');
	var li_reset = jQuery('<li class="reset" onclick="t3_profile_reset(\'' + id
			+ '\')">' + Drupal.t("Reset to default") + '</li>');
	var li_rename = jQuery('<li class="rename" onclick="t3_profile_rename(\''
			+ id + '\')">' + Drupal.t("Rename") + '</li>');
	var li_del = jQuery('<li class="delete" onclick="t3_profile_delete(\'' + id
			+ '\')">' + Drupal.t("Delete") + '</li>');

	li_clone.appendTo(ul);

	if (profiles['profile_type'] == 'override') {
		li_reset.appendTo(ul);
	}
	if (profiles['profile_type'] == 'local') {
		li_rename.appendTo(ul);
		li_del.appendTo(ul);
	}

	jQuery('#jd-profile-action-dialog').html(ul);

	jQuery('#jd-profile-action-dialog').css( {
		left : window.mouseXPos + 'px',
		top : window.mouseYPos + 'px'
	});
	jQuery('#jd-profile-action-dialog').show();
}

function t3_profile_ajax_add(ev) {
	var value = jQuery('#t3_profile_name_edit').attr('value');

	if (jQuery.trim(value) == '') {
		alert(Drupal.t('Profile name cannot be empty.'));
		return false;
	}

	value = t3_final_filename(value);

	if (t3_profiles[value] != undefined) {
		alert(Drupal.t('Profile "' + value
				+ '" already exists. Please enter another profile name.'));
		return false;
	}

	if (jQuery.trim(value) == '') {
		alert(Drupal
				.t('Profile cannot be created. No template specified or profile name contains invalid character(s).'));
		return false;
	}

	var data = {
		'theme_key' : t3_current_theme,
		'profile' : value,
		't3_task' : 'add_profile'
	};
	url = 'index.php?q=admin/build/themes/settings/' + t3_current_theme;

	jQuery(ev.target).addClass('t3-loading');
	jQuery.ajax( {
		type : "POST",
		url : url,
		data : data,
		success : function(respTxt) {
			var reps = Drupal.parseJson(respTxt);
			if (reps['success']) {
				t3_profile_add_effect(reps);
			}

			t3_display_message(reps['message']);

			jQuery(ev.target).removeClass('t3-loading');
			jQuery('#t3_profile_dialog_new').dialog('close');
		}
	});
}

function t3_profile_add_effect(resp) {
	var name = resp['name'];

	var li = jQuery('<li id="t3-admin-profile-' + name
			+ '" class="jd-profile active"></li>');

	var newBtn = jQuery("#jd-theme-setting  ul.profile > li.jd-new-profile");
	var lis = jQuery("#jd-theme-setting  ul.profile > li");
	;

	lis.each(function(index, item) {
		if (jQuery(item).hasClass('active'))
			jQuery(item).removeClass('active');
	});

	// add click event
	li
			.click(function() {
				var alis = jQuery("#jd-theme-setting ul.profile > li");
				alis.each(function(index, oli) {
					jQuery(oli).removeClass('active');
					var action = jQuery(oli).find('span');

					if (jQuery(action).hasClass('jd-profile-action')) {
						jQuery(action).remove();
					}
				});
				jQuery(this).addClass('active');
				var action = jQuery('<span class="jd-profile-action">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>');
				action.appendTo(jQuery(this));

				action.click(function(event) {
					t3_profile_action_show(name);
					event.stopPropagation();
				});
				t3_profile_select(this.id);
			});

	li
			.html('<a id="t3-admin-profile-a-'
					+ name
					+ '" href="javascript:void(0)">'
					+ name
					+ '</a><span class="jd-profile-action">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>');
	span = li.find('span');
	jQuery(span).click(function(event) {
		t3_profile_action_show(name);
		event.stopPropagation();
	});
	li.insertBefore(newBtn);

	// clone default profile
	t3_profiles[name] = new Object();
	t3_profiles[name]['name'] = name;
	t3_profiles[name]['profile_type'] = 'local';

	t3_old_profiles[name] = new Object();
	t3_old_profiles[name]['name'] = name;
	t3_old_profiles[name]['profile_type'] = 'local';

	t3_current_profile = name;

	t3_profile_select(name);
	// set empty textbox for using next task of profile (new, clone, rename)

	// add to general setting
	var gul = jQuery('#t3_general_profile_dialog ul');

	var li = jQuery('<li>' + name + '</li>');
	li.appendTo(jQuery(gul));
}

function t3_profile_clone(name) {
	jQuery('#t3_profile_dialog_new').dialog('option', 'title',
			Drupal.t('Clone profile :') + name);
	jQuery('#t3_profile_name_source').attr('value', name);
	jQuery('#t3_profile_name_task').attr('value', 'clone');
	jQuery('#t3_profile_dialog_new').dialog('open');
	jQuery('#t3_profile_name_edit').attr('value', name + '-clone');
}

function t3_profile_clone_submit(ev) {
	var source = jQuery('#t3_profile_name_source').attr('value');

	var value = jQuery('#t3_profile_name_edit').attr('value');

	if (jQuery.trim(value) == '') {
		alert(Drupal.t('Profile name cannot be empty.'));
		return false;
	}
	value = t3_final_filename(value);

	if (t3_profiles[value] != undefined) {
		alert(Drupal.t('Profile "' + value
				+ '" already exists. Please enter another profile name.'));
		return false;
	}

	if (jQuery.trim(value) == '') {
		alert(Drupal
				.t('Profile cannot be created. No template specified or profile name contains invalid character(s).'));
		return false;
	}

	var data = {
		'theme_key' : t3_current_theme,
		'profile' : value,
		'source' : source,
		't3_task' : 'clone_profile'
	};

	url = 'index.php?q=admin/build/themes/settings/' + t3_current_theme;

	jQuery(ev.target).addClass('t3-loading');
	jQuery.ajax( {
		type : "POST",
		url : url,
		data : data,
		success : function(respTxt) {
			var reps = Drupal.parseJson(respTxt);

			if (reps['success']) {
				t3_profile_clone_effect(reps);
			}

			t3_display_message(reps['message']);
			jQuery(ev.target).removeClass('t3-loading');
			jQuery('#t3_profile_dialog_new').dialog('close');
		}
	});
}

function t3_profile_clone_effect(resp) {
	var value = resp['name'];

	var source = resp['source'];

	var li = jQuery('<li id="t3-admin-profile-' + value
			+ '" class="jd-profile active"></li>');

	var newBtn = jQuery("#jd-theme-setting  ul.profile > li.jd-new-profile");
	var lis = jQuery("#jd-theme-setting  ul.profile > li");
	;

	lis.each(function(index, item) {
		if (jQuery(item).hasClass('active'))
			jQuery(item).removeClass('active');
	});

	// add click event
	li
			.click(function() {
				var alis = jQuery("#jd-theme-setting  ul.profile > li");
				alis.each(function(index, oli) {
					jQuery(oli).removeClass('active');
					var action = jQuery(oli).find('span');

					if (jQuery(action).hasClass('jd-profile-action')) {
						jQuery(action).remove();
					}
				});
				jQuery(this).addClass('active');
				var action = jQuery('<span class="jd-profile-action">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>');
				action.appendTo(jQuery(this));

				action.click(function(event) {
					t3_profile_action_show(value);
					event.stopPropagation();
				});
				t3_profile_select(this.id);
			});

	li
			.html('<a id="t3-admin-profile-a-'
					+ value
					+ '" href="javascript:void(0)">'
					+ value
					+ '</a><span class="jd-profile-action">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>');
	span = li.find('span');
	jQuery(span).click(function(event) {
		t3_profile_action_show(value);
		event.stopPropagation();
	});
	li.insertBefore(newBtn);

	// clone default profile
	t3_profiles[value] = new cloneObject(t3_profiles[source]);
	t3_profiles[value]['name'] = value;
	t3_profiles[value]['profile_type'] = 'local';

	t3_old_profiles[value] = new cloneObject(t3_old_profiles[source]);
	t3_old_profiles[value]['name'] = value;
	t3_old_profiles[value]['profile_type'] = 'local';

	t3_current_profile = value;
	t3_profile_select(value);

	// add to general setting
	var gul = jQuery('#t3_general_profile_dialog ul');

	var li = jQuery('<li>' + value + '</li>');
	li.appendTo(jQuery(gul));
}

function t3_profile_rename(name) {
	jQuery('#t3_profile_dialog_new').dialog('option', 'title',
			Drupal.t('Rename profile :') + name);
	jQuery('#t3_profile_name_source').attr('value', name);
	jQuery('#t3_profile_name_edit').attr('value', name);
	jQuery('#t3_profile_name_task').attr('value', 'rename');
	jQuery('#t3_profile_dialog_new').dialog('open');
}

function t3_profile_rename_submit(ev) {
	var source = jQuery('#t3_profile_name_source').attr('value');

	var value = jQuery('#t3_profile_name_edit').attr('value');

	var u_profiles = [];
	for (gname in t3_general) {
		if (jQuery.trim(t3_general[gname]) == source) {
			u_profiles[u_profiles.length] = gname;
		}

	}

	if (u_profiles.length) {
		var msg = 'This profile can not be renamed because it is being used by page(s):';
		for (i = 0; i < u_profiles.length; i++) {
			msg += u_profiles[i].replace(/&lt;/, '<').replace('&gt;', '>');
			if (u_profiles.length > i + 1)
				msg += ',';
		}
		msg += '. You can only rename the profile if it is not assigned to any page.';
		alert(msg);
		return;
	}

	var source = jQuery('#t3_profile_name_source').attr('value');

	var value = jQuery('#t3_profile_name_edit').attr('value');

	value = t3_final_filename(value);

	if (source == value) {
		jQuery(ev.target).removeClass('t3-loading');
		jQuery('#t3_profile_dialog_new').dialog('close');
		return;
	}

	if (t3_profiles[value] != undefined) {
		alert(Drupal.t('Profile "' + value
				+ '" already exists. Please enter another profile name.'));
		return false;
	}

	if (jQuery.trim(value) == '') {
		alert(Drupal
				.t('Profile cannot be created. No template specified or profile name contains invalid character(s).'));
		return false;
	}

	var data = {
		'theme_key' : t3_current_theme,
		'profile' : value,
		'source' : source,
		't3_task' : 'rename_profile'
	};

	url = 'index.php?q=admin/build/themes/settings/' + t3_current_theme;

	jQuery(ev.target).addClass('t3-loading');
	jQuery.ajax( {
		type : "POST",
		url : url,
		data : data,
		success : function(respTxt) {
			var reps = Drupal.parseJson(respTxt);

			if (reps['success']) {
				t3_profile_rename_effect(reps);
			}

			t3_display_message(reps['message']);
			jQuery(ev.target).removeClass('t3-loading');
			jQuery('#t3_profile_dialog_new').dialog('close');
		}
	});

}

function t3_profile_rename_effect(resp) {
	var source = resp['source'];

	var value = resp['name'];

	var as = jQuery("#jd-theme-setting  ul.profile > li > a");
	var li = null;
	as.each(function(index, item) {
		if (jQuery(item).text() == source) {
			jQuery(item).text(value);

			jQuery(item).attr('id', 't3-admin-profile-a-' + value);
			jQuery(item).parent().attr('id', 't3-admin-profile-' + value);
			var action = jQuery(item).next();

			jQuery(action).unbind('click');

			jQuery(action).click(function(event) {
				t3_profile_action_show(value);
				event.stopPropagation();
			});

			li = jQuery(item).parent();
		}
	});

	jQuery(li).unbind('click');
	jQuery(li)
			.click(
					function() {
						var alis = jQuery("#jd-theme-setting  ul.profile > li");
						alis.each(function(index, oli) {
							jQuery(oli).removeClass('active');
							var action = jQuery(oli).find('span');

							if (jQuery(action).hasClass('jd-profile-action')) {
								jQuery(action).remove();
							}
						});
						jQuery(this).addClass('active');
						var action = jQuery('<span class="jd-profile-action">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>');
						action.appendTo(jQuery(this));

						action.click(function(event) {
							t3_profile_action_show(value);
							event.stopPropagation();
						});
						t3_profile_select(value);
						t3_profile_build_suffix_table();
					});

	// clone default profile
	t3_profiles[value] = new cloneObject(t3_profiles[source]);

	t3_profiles[value]['name'] = value;
	delete t3_profiles[source];

	t3_old_profiles[value] = new cloneObject(t3_old_profiles[source]);
	t3_old_profiles[value]['name'] = value;
	delete t3_old_profiles[source];

	t3_current_profile = value;
	// effect to general settings
	var glis = jQuery('#t3_general_profile_dialog li');

	glis.each(function(i, li) {
		if (jQuery.trim(jQuery(li).text()) == source) {
			jQuery(li).text(value);
		}
	});
}

function t3_profile_delete(name) {
	var u_profiles = [];
	for (gname in t3_general) {
		if (jQuery.trim(t3_general[gname]) == name) {
			u_profiles[u_profiles.length] = gname;
		}

	}

	if (u_profiles.length) {
		var msg = 'This profile can not be deleted because it is being used by page(s):';
		for (i = 0; i < u_profiles.length; i++) {
			msg += u_profiles[i].replace(/&lt;/, '<').replace('&gt;', '>');
			if (u_profiles.length > i + 1)
				msg += ',';
		}
		msg += '. You can only delete the profile if it is not assigned to any page.';
		alert(msg);
		return;
	}

	var del = confirm(Drupal.t('Are you sure you want to delete the profile:')
			+ name);
	if (del) {
		var data = {
			'theme_key' : t3_current_theme,
			'profile' : name,
			't3_task' : 'delete_profile'
		};
		url = 'index.php?q=admin/build/themes/settings/' + t3_current_theme;

		jQuery
				.ajax( {
					type : "POST",
					url : url,
					data : data,
					success : function(respTxt) {
						var reps = Drupal.parseJson(respTxt);

						if (reps['success']) {
							// delete li object
							var as = jQuery("#jd-theme-setting  ul.profile > li > a");

							as.each(function(index, item) {
								if (jQuery(item).text() == name) {
									var li = jQuery(item).parent();
									jQuery(li).remove();
								}
							});

							// delete t3_profile_object

							delete t3_profiles[reps['name']];
							delete t3_old_profiles[reps['name']];
							// delete from general list
							var glis = jQuery('#t3_general_profile_dialog li');

							glis
									.each(function(i, li) {
										if (jQuery.trim(jQuery(li).text()) == reps['name']) {
											jQuery(li).remove();
										}
									});
							// remove profile in general page
							var gdialog = jQuery('#t3_general_profile_dialog');
							var lis = gdialog.find('li');

							lis.each(function(i, gli) {
								if (jQuery.trim(jQuery(gli).text()) == name) {
									jQuery(gli).remove();
								}
							});

							jQuery('#t3-admin-profile-default').addClass(
									'active');
							var action = jQuery('<span class="jd-profile-action">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>');
							action
									.appendTo(jQuery(jQuery('#t3-admin-profile-default')));

							action.click(function(event) {
								t3_profile_action_show(value);
								event.stopPropagation();
							});

							t3_profile_select('default');
						}

						t3_display_message(reps['message']);
					}
				});

	}
}

function t3_profile_reset(name) {
	var reset = confirm(Drupal
			.t('Are you sure you want to reset to default settings the profile:')
			+ name);

	if (reset) {
		var data = {
			'theme_key' : t3_current_theme,
			'profile' : name,
			't3_task' : 'reset_profile'
		};
		url = 'index.php?q=admin/build/themes/settings/' + t3_current_theme;

		jQuery.ajax( {
			type : "POST",
			url : url,
			data : data,
			success : function(respTxt) {
				var reps = Drupal.parseJson(respTxt);

				if (reps['success']) {
					// delete li object
					delete t3_profiles[name];

					t3_profiles[name] = reps['value'];
					t3_profiles[name]['profile_type'] = 'core';

					t3_profile_select('default');
					t3_profile_select(name);
				}

				t3_display_message(reps['message']);

			}
		});

	}
}

function t3_profile_select(name) {
	name = name.replace(/t3-admin-profile-/g, '');
	name = jQuery.trim(name);
	t3_current_profile = name;
	// need to assign value fron selected profile

	var profiles = t3_profiles[name];

	t3_profile_elements
			.each(function(index, element) {
				var elm_name = element.name;

				if (/block_/.test(elm_name)) {
					return;
				}

				// check if element is array
				if (profiles[elm_name] != undefined) {
					jQuery(element).attr('value', profiles[elm_name]);
				} else {
					if (t3_profiles['default'][elm_name] != undefined) {
						jQuery(element).attr('value',
								t3_profiles['default'][elm_name]);
					} else {

						jQuery(element).attr('value',
								t3_default_vals['profile'][elm_name]);
					}

				}

				if (/gfont_[a-z]+.style/.test(elm_name)) {
					if (profiles[elm_name] != undefined) {
						jQuery(element).attr('value',
								profiles[elm_name].replace(/\\n/g, '\n'));
						jQuery(element).show();
						// find input element
						var ip = jQuery(element).parent().children('input');
						jQuery(ip).attr('checked', true);
					} else {
						jQuery(element).attr('value', '');
						jQuery(element).hide();
						// find input element
						var ip = jQuery(element).parent().children('input');
						jQuery(ip).attr('checked', false);
					}
				}

				if (/option_/.test(elm_name)) {
					if (profiles[elm_name] == 1) {
						jQuery(element).attr('checked', true);
					}

					if (profiles[elm_name] == 0) {
						jQuery(element).attr('checked', false);
					}
				}
			});

	// sub-themes proccess
	var avail_themes = jQuery('#avail-themes');
	var selected_themes = jQuery('#selected-themes');

	var childs = selected_themes.children();
	var themes = profiles['themes'];

	childs.each(function(index, li) {
		jQuery(li).remove();
	});

	var childs = avail_themes.find('input[type=checkbox]');
	childs.each(function(index, checkbox) {

		if (jQuery(checkbox).attr('value') != 'default') {
			checkbox.checked = false;
		} else {
			checkbox.checked = true;
		}
	});

	if (themes) {
		themes = themes.split(',');

		for (i = 0; i < themes.length; i++) {
			var theme = jQuery.trim(themes[i]);
			var childs = avail_themes.find('input[value=' + theme + ']');

			childs
					.each(function(index, checkbox) {
						checkbox.checked = true;

						li = jQuery(checkbox).next();
						if (li.text() != 'default') {
							var addItem = jQuery('<span id="' + li.text()
									+ '" class="jd-sub-theme">' + li.text()
									+ '</span>');
							addItem.appendTo(jQuery('#selected-themes'));
						}
					});
		}
	} else {
		themes = t3_profiles['default']['themes'];
		if (themes) {
			themes = themes.split(',');

			for (i = 0; i < themes.length; i++) {
				var theme = jQuery.trim(themes[i]);
				var childs = avail_themes.find('input[value=' + theme + ']');

				childs.each(function(index, checkbox) {
					checkbox.checked = true;

					li = jQuery(checkbox).next();
					if (li.text() != 'default') {
						var addItem = jQuery('<span id="' + li.text()
								+ '" class="jd-sub-theme">' + li.text()
								+ '</span>');
						addItem.appendTo(jQuery('#selected-themes'));
					}
				});
			}
		}
	}

	// always check default themes

	addCheckbox();
}

function addCheckbox() {
	jQuery('.cb-span').unbind('click');
	jQuery('.ja-delete').each(function() {
		jQuery(this).css('visibility', '');
	});
	var form_items = jQuery('#theme-profiles').find('.form-item');

	form_items
			.each(function(index, item) {
				if (jQuery.trim(t3_current_profile) != 'default') {
					if (item.id != 'edit-pages-wrapper') {
						var checkbox = jQuery(item).find('span.cb-span');

						if (!checkbox.length) {
							checkbox = jQuery('<span class="cb-span"></span>');
							if (item.tagName == 'TR') {
								var tds = jQuery(item).find('td');
								td = jQuery(tds)[3];
								checkbox.appendTo(jQuery(td));
							} else {
								var gfont = jQuery(item).find('.gfont-custom');
								if (gfont.length) {
									checkbox.insertBefore(jQuery(gfont));
								} else {
									checkbox.appendTo(jQuery(item));
								}
							}
						}

						// find input name in this item
						var input = jQuery(item).find(':input');
						var name = jQuery(input).attr('name');

						if (t3_profiles[t3_current_profile][name] != undefined) {
							jQuery(checkbox).addClass('cb-span-checked');
							jQuery(item).removeClass('disabled');
							var inputs = jQuery(item).find(':input');
							jQuery(inputs).attr('disabled', false);

						} else {
							jQuery(checkbox).removeClass('cb-span-checked');
							jQuery(item).addClass('disabled');
							var inputs = jQuery(item).find(':input');
							jQuery(inputs).attr('disabled', true);
							jQuery('.ja-delete').each(function() {
								jQuery(this).css('visibility', 'hidden');
							});

						}

						if (jQuery(item).hasClass('jd-subtheme-list')) {
							if (t3_profiles[t3_current_profile]['themes'] != undefined) {
								jQuery(checkbox).addClass('cb-span-checked');
								jQuery(item).removeClass('disabled');
								jQuery("#selected-themes").sortable('enable');
							} else {
								jQuery(checkbox).removeClass('cb-span-checked');

								jQuery(item).addClass('disabled');
								jQuery("#selected-themes").sortable('disable');
							}
						}
					}
				} else {
					var checkbox = jQuery(item).find('span.cb-span');

					if (checkbox.length) {
						jQuery(checkbox).remove();
					}

					jQuery(item).removeClass('disabled');
					jQuery(item).removeClass('enabled');
					var inputs = jQuery(item).find(':input');
					jQuery(inputs).attr('disabled', false);
				}

			});
	if (jQuery.trim(t3_current_profile) != 'default') {
		// Handle for block suffix
		if (t3_profiles[t3_current_profile]['block']) {
			jQuery('.block-class-suffix-handle .cb-span').addClass(
					'cb-span-checked');
			jQuery('.block-class-suffix-handle').removeClass('disabled');
			jQuery('#block_item').attr('disabled', false);
			jQuery('#block_suffix').attr('disabled', false);
		} else {
			jQuery('.block-class-suffix-handle .cb-span').removeClass(
					'cb-span-checked');
			jQuery('.block-class-suffix-handle').addClass('disabled');
			jQuery('#block_item').attr('disabled', true);
			jQuery('#block_suffix').attr('disabled', true);
			jQuery('.ja-delete').each(function() {
				jQuery(this).css('visibility', 'hidden');
			});

		}
	}
	// OK, add event for span checkbox
	jQuery('.cb-span')
			.click(
					function() {

						var parent = jQuery(this).parent();

						if (jQuery(parent).attr('tagName') == 'TD') {
							parent = jQuery(parent).parent();
						}

						var Elm = jQuery(parent).find(':input');

						var ElmName = jQuery(Elm).attr('name');

						var inputs = jQuery(parent).find(':input');
						if (jQuery(this).hasClass('cb-span-checked')) {
							jQuery('.enabled .ja-delete').each(function() {
								jQuery(this).css('visibility', 'hidden');
							});
							jQuery(inputs).attr('disabled', true);
							jQuery(parent).addClass('disabled');
							jQuery(parent).removeClass('enabled');

							if (Elm.length > 1) {
								// if have more than one input in this item
								for (i = 0; i < Elm.length; i++) {

									var Elm_name = jQuery(Elm[i]).attr('name');
									delete t3_profiles[t3_current_profile][Elm_name];
									// now reset to default
									if (/[a-z]+.extra/.test(Elm_name)) {
										jQuery(Elm[i]).attr('checked', false);
									} else if (/gfont_[a-z]+.style/
											.test(Elm_name)) {
										jQuery(Elm[i]).attr('value', '');
										jQuery(Elm[i]).hide();
									} else {
										if (t3_profiles['default'][Elm_name] != undefined) {
											jQuery(Elm[i])
													.attr(
															'value',
															t3_profiles['default'][Elm_name]);
										} else {
											jQuery(Elm[i])
													.attr(
															'value',
															t3_default_vals['profile'][Elm_name]);
										}
									}
								}
							} else {
								delete t3_profiles[t3_current_profile][ElmName];

								if (t3_profiles['default'][ElmName] != undefined) {
									jQuery(Elm).attr('value',
											t3_profiles['default'][ElmName]);
								} else {
									jQuery(Elm)
											.attr(
													'value',
													t3_default_vals['profile'][ElmName]);
								}
							}

						} else {
							jQuery('.disabled .ja-delete').each(function() {
								jQuery(this).css('visibility', '');
							});
							jQuery(parent).removeClass('disabled');
							jQuery(parent).addClass('enabled');
							jQuery(inputs).attr('disabled', false);

							if (Elm.length > 1) {
								// if have more than one input in this item
								for (i = 0; i < Elm.length; i++) {
									var Elm_name = jQuery(Elm[i]).attr('name');
									t3_profiles[t3_current_profile][Elm_name] = t3_profiles['default'][Elm_name] == undefined ? t3_default_vals['profile'][Elm_name]
											: t3_profiles['default'][Elm_name];
									if (t3_profiles[t3_current_profile][Elm_name] == undefined
											|| t3_profiles[t3_current_profile][Elm_name] == '') {
										delete t3_profiles[t3_current_profile][Elm_name];
									}
								}
							} else {
								t3_profiles[t3_current_profile][ElmName] = t3_profiles['default'][ElmName] == undefined ? t3_default_vals['profile'][ElmName]
										: t3_profiles['default'][ElmName];
							}
						}

						if (parent.hasClass('jd-subtheme-list')) {
							if (jQuery(this).hasClass('cb-span-checked')) {
								jQuery("#selected-themes").sortable('disable');
								delete t3_profiles[t3_current_profile]['themes'];
							} else {
								jQuery("#selected-themes").sortable('enable');
								t3_profiles[t3_current_profile]['themes'] = t3_profiles['default']['themes'];
							}
						}
						jQuery(this).toggleClass('cb-span-checked');

						t3_profile_tab_status();
					});

}

function t3_profile_element_change(elm) {
	var name = jQuery(elm).attr('name');
	if (/block_/.test(name))
		return;

	if (/[a-z]+.extra/.test(name)) {
		return;
	}

	var old_value = t3_old_profiles[t3_current_profile][name];
	var new_value = jQuery(elm).attr('value');
	if (jQuery(elm).attr('type') == 'checkbox') {
		new_value = elm.checked ? 1 : 0;
	}

	if (/gfont_[a-z]+.style/.test(name)) {
		new_value = new_value.replace(/[\r\n]+/g, "\\n");
	}

	t3_profiles[t3_current_profile][name] = new_value;

	t3_profile_tab_status();
}

function t3_profile_tab_status() {
	// for google custom font
	if (!t3_compare_array(t3_profiles[t3_current_profile],
			t3_old_profiles[t3_current_profile])) {
		// find profile tab and add changed class to it
		var a = jQuery("#jd-theme-setting  ul.secondary > li a#t3-admin-profile-a-"
				+ t3_current_profile);

		jQuery(a).addClass('changed');
		t3_tab_change('profiles');
	} else {
		// find profile tab and add changed class to it
		var a = jQuery("#jd-theme-setting  ul.secondary > li a#t3-admin-profile-a-"
				+ t3_current_profile);

		jQuery(a).removeClass('changed');
	}

	// now check for all profiles
	var allchanged = false;
	for (pname in t3_profiles) {
		if (!t3_compare_array(t3_profiles[pname], t3_old_profiles[pname])) {
			allchanged = true;
			break;
		}
	}

	if (!allchanged) {
		t3_tab_nochange('profiles');
	}
}

function t3_new_profile() {

	jQuery('#dialog-profile').dialog("open");
}

function t3_new_profile_add() {

}

// ///////////////////////////////////////////////////
// /////////// LAYOUT FUNCTION ////////////////////
// ///////////////////////////////////////////////////
function t3_layout_init() {
	// init edit dialog
	var t3_layout_dialog = jQuery('<div id="t3_layout_dialog_edit"></div>');
	// add textarea here
	var html = '<form id="t3_layout_edit_form" method="post" action="">';
	html += '<span>' + Drupal.t('Name') + ':</span>';
	html += '<input type="textbox" name="t3_layout_name_edit" id="t3_layout_name_edit" /><br/><br/>';
	html += '<textarea id="t3_layout_content_edit" name="t3_layout_content" class="content-layout"></textarea>';
	html += '<input type="hidden" name="t3_task" value="store_layout" />';
	html += '<input type="hidden" name="theme" value="' + t3_current_theme
			+ '" />';
	html += '<input type="hidden" name="t3_layout_name" id="t3_layout_name_value" value="" />';
	html += '</form>';

	t3_layout_dialog.html(html);
	var alerted = false;
	t3_layout_dialog
			.dialog( {
				title : '',
				width : 600,
				height : 450,
				draggable : true,
				open : function() {
					alerted = false;
				},
				buttons : {
					"Save" : function(ev, ui) {
						// check if have nothing to change, confirm and exit
						// dialog

						var old_name = jQuery.trim(jQuery(
								'#t3_layout_name_value').attr('value'));
						var name = jQuery.trim(jQuery('#t3_layout_name_edit')
								.attr('value'));
						name = t3_final_filename(name);
						var content = jQuery.trim(jQuery(
								'#t3_layout_content_edit').attr('value'));

						if (jQuery.trim(jQuery('#t3_layout_name_edit').attr(
								'value'))
								&& jQuery.trim(name) == '') {
							alert(Drupal
									.t('Layout cannot be created. No template specified or layout name contains invalid character(s).'));
							alerted = true;
							return;
						}
						if (jQuery.trim(name) == '') {
							alert(Drupal.t('Layout name cannot be empty.'))
							alerted = true;
							return;
						}

						// if (jQuery.trim(content) == '') {
						// alert(Drupal.t('Layout content cannot be empty!'))
						// return;
						// }

						var change = 1;
						if (old_name == name) {
							var old_content = t3_layouts[name]['content'];

							old_content = old_content.replace(/\n/g, '')
									.replace(/\t/g, '').replace(/\r/g, '');

							content = content.replace(/\n/g, '').replace(/\t/g,
									'').replace(/\r/g, '');

							if (old_content == content) {
								change = 0;

								jQuery(this).dialog("close");
								return false;
							}
						}
						if (change) {
							if (old_name != name) {
								var u_profiles = [];
								for (pname in t3_profiles) {
									var used = false;

									used = used
											|| (t3_profiles[pname]['layout_desktop'] && t3_profiles[pname]['layout_desktop'] == old_name);
									used = used
											|| (t3_profiles[pname]['layout_handheld'] && t3_profiles[pname]['layout_handheld'] == old_name);
									used = used
											|| (t3_profiles[pname]['layout_iphone'] && t3_profiles[pname]['layout_iphone'] == old_name);

									if (used) {

										u_profiles[u_profiles.length] = pname;
									}
								}

								if (u_profiles.length) {
									var msg = 'This layout can not be renamed because it is being used by profile(s):';
									for (i = 0; i < u_profiles.length; i++) {
										msg += u_profiles[i];
										if (u_profiles.length > i + 1)
											msg += ',';
									}
									msg += '. You can only rename the layout if it is not used by any profile.';
									alert(msg);
									return;
								}

							}
							if (old_name != name
									&& t3_layouts[name] != undefined) {
								alert(Drupal
										.t('Layout "'
												+ name
												+ '" already exists. Please enter another layout name.'));
								alerted = true;
							} else {
								t3_layout_ajax_save(ev);
							}
						}
					},
					"Cancel" : function() {
						jQuery(this).dialog("close");
					}
				},
				beforeclose : function() {
					if (t3_layout_current_task == 'save') {
						t3_layout_current_task = '';
						return true;
					}
					// check if have nothing to change, confirm and exit dialog
					var old_name = jQuery.trim(jQuery('#t3_layout_name_value')
							.attr('value'));
					var name = jQuery.trim(jQuery('#t3_layout_name_edit').attr(
							'value'));
					var content = jQuery.trim(jQuery('#t3_layout_content_edit')
							.attr('value'));

					old_content = '';
					if (t3_layouts[name]) {
						old_content = t3_layouts[name]['content'];
					}

					old_content = old_content.replace(/\n/g, '').replace(/\t/g,
							'').replace(/\r/g, '');

					content = content.replace(/\n/g, '').replace(/\t/g, '')
							.replace(/\r/g, '');

					if ((jQuery.trim(old_name) != jQuery.trim(name) || jQuery
							.trim(old_content) != jQuery.trim(content))) {
						var close = confirm(Drupal
								.t('There are some changes, do you want to close without saving them?'));
						if (!close)
							return false;
					}
				},
				autoOpen : false
			});

	// init rename, save as ...layout dialog
	var t3_layout_dialog_name = jQuery('<div id="t3_layout_dialog_name"></div>');

	var html = '<form id="t3_layout_simple_form" method="post" action="">';
	html += '<span>' + Drupal.t('Name') + ':</span>';
	html += '<input type="textbox" name="t3_layout_simple_name" id="t3_layout_simple_name" />';
	html += '<input type="hidden" name="t3_layout_task" id="t3_layout_task" value="clone" />';
	html += '<input type="hidden" name="t3_layout_source" id="t3_layout_source" value="" />';
	html += '</form>';

	t3_layout_dialog_name.html(html);

	t3_layout_dialog_name
			.dialog( {
				title : '',
				width : 250,
				height : 120,
				buttons : {
					"Ok" : function(ev, ui) {

						var name = jQuery('#t3_layout_simple_name').attr(
								'value');

						if (t3_layouts[name] != undefined) {
							alert(Drupal
									.t('Layout '
											+ name
											+ ' already exists. Please enter another layout name.'));
						} else {
							t3_layout_simple_submit(ev);
						}

					},
					"Cancel" : function() {
						jQuery(this).dialog("close");
					}
				},

				autoOpen : false
			});

	// dont need to submit form
	jQuery('#t3_layout_edit_form').submit(function() {
		return false;
	});
}

function t3_layout_ajax_save(ev) {
	var name = t3_final_filename(jQuery('#t3_layout_name_edit').attr('value'));

	if (jQuery.trim(name) == '') {
		alert(Drupal
				.t('Layout cannot be created. No template specified or layout name contains invalid character(s).'));
		return;
	}

	jQuery('#t3_layout_name_edit').attr('value', name);
	strData = jQuery("#t3_layout_edit_form").serialize();
	url = 'index.php?q=admin/build/themes/settings/' + t3_current_theme;

	jQuery(ev.target).addClass('t3-loading');
	jQuery
			.ajax( {
				type : "POST",
				url : url,
				data : strData,
				success : function(respTxt) {

					var respArr = Drupal.parseJson(respTxt);

					if (respArr['success']) {
						if (respArr['state'] == 'new') {

							var value = jQuery('#t3_layout_content_edit').attr(
									'value');

							t3_layout_add(name, value);
						} else if (respArr['state'] == 'edit') {
							if (respArr['rename']) {
								t3_edit_layout_effect(respArr['old_name'],
										respArr['new_name'], 'rename');
							} else if (respArr['type'] == 'override') {
								t3_edit_layout_effect(respArr['old_name'],
										respArr['new_name'], 'override');
							}
							t3_layouts[t3_current_layout]['content'] = jQuery(
									'#t3_layout_content_edit').attr('value');
							// effect edit layout to front here
						}

					}
					t3_layout_current_task = 'save';
					jQuery('#t3_layout_dialog_edit').dialog('close');
					t3_display_message(respArr['message']);
					jQuery(ev.target).removeClass('t3-loading');
				}
			});
}

function t3_layout_add(name, value) {
	t3_current_layout = name;
	t3_layouts[t3_current_layout] = {
		'name' : name,
		'content' : value,
		'type' : 'local'
	};
	t3_edit_layout_effect(t3_current_layout, t3_current_layout, 'add');
}
function t3_layout_delete(name, span) {
	// when change layout name, we cannot using this name, so need to change
	// name

	// we need to get list of profile are using this layout
	// give affect

	var u_profiles = [];
	for (pname in t3_profiles) {
		var used = false;

		used = used
				|| (t3_profiles[pname]['layout_desktop'] && t3_profiles[pname]['layout_desktop'] == name);
		used = used
				|| (t3_profiles[pname]['layout_handheld'] && t3_profiles[pname]['layout_handheld'] == name);
		used = used
				|| (t3_profiles[pname]['layout_iphone'] && t3_profiles[pname]['layout_iphone'] == name);

		if (used) {

			u_profiles[u_profiles.length] = pname;
		}
	}

	if (u_profiles.length) {
		var msg = 'This layout can not be deleted because it is being used by profile(s):';
		for (i = 0; i < u_profiles.length; i++) {
			msg += u_profiles[i];
			if (u_profiles.length > i + 1)
				msg += ',';
		}
		msg += '. You can only delete the layout if it is not used by any profile.';
		alert(msg);
		return;
	}
	var del = confirm(Drupal.t('Are you sure you want to delete this layout?'));

	if (del) {
		url = 'index.php?q=admin/build/themes/settings/' + t3_current_theme;

		jQuery(span).removeClass('jd-delete');
		jQuery(span).addClass('t3-loading');
		jQuery.ajax( {
			type : "POST",
			url : url,
			data : 't3_task=delete_layout&name=' + name + '&theme='
					+ t3_current_theme,
			success : function(respTxt) {
				respArr = Drupal.parseJson(respTxt);
				if (respArr['success']) {
					t3_layouts[name] = null;
					t3_edit_layout_effect(name, name, 'delete', span);

				}

				t3_display_message(respArr['message']);

				jQuery(span).addClass('jd-delete');
				jQuery(span).removeClass('t3-loading');
			}
		});
	}
}

function t3_layout_reset(name, span) {
	var reset = confirm(Drupal
			.t('Are you sure you want to reset this layout to default settings?'));

	if (reset) {
		jQuery(span).removeClass('jd-reset');
		jQuery(span).addClass('reseting');
		jQuery(span).addClass('t3-loading');
		url = 'index.php?q=admin/build/themes/settings/' + t3_current_theme;

		jQuery.ajax( {
			type : "POST",
			url : url,
			data : 't3_task=reset_layout&name=' + name + '&theme='
					+ t3_current_theme,
			success : function(respTxt) {
				respArr = Drupal.parseJson(respTxt);
				if (respArr['success']) {
					t3_layouts[name]['content'] = respArr['content'];
					t3_edit_layout_effect(name, 'core', 'reset', span);

				}
				t3_display_message(respArr['message']);
				jQuery(span).removeClass('t3-loading');
				jQuery(span).removeClass('reseting');
				jQuery(span).addClass('jd-reset');
			}
		});
	}
}

function t3_layout_clone(name) {
	// set title for dialog
	jQuery('#t3_layout_dialog_name').dialog('option', 'title',
			'Clone layout:' + Drupal.t(name));

	// set layout-task and layout-source for form
	jQuery('#t3_layout_task').attr('value', 'clone_layout');
	// find clone name valid for this
	var clone_name = name + '-clone';
	var i = 1;
	while (t3_layouts[clone_name] != undefined) {
		clone_name = clone_name + '-' + i;
	}
	jQuery('#t3_layout_simple_name').attr('value', clone_name);
	jQuery('#t3_layout_source').attr('value', name);
	jQuery('#t3_layout_dialog_name').dialog('open');
}

function t3_layout_simple_submit(ev) {
	var name = jQuery('#t3_layout_simple_name').attr('value');

	if (jQuery.trim(name) == '') {
		alert(Drupal.t('Layout name cannot be empty.'));
		return true;
	}

	name = t3_final_filename(name);

	if (jQuery.trim(name) == '') {
		alert(Drupal
				.t('Layout cannot be created. No template specified or layout name contains invalid character(s).'));
		return true;
	}

	jQuery('#t3_layout_simple_name').attr('value', name);
	strData = jQuery("#t3_layout_simple_form").serialize();

	var t3_task = jQuery('#t3_layout_task').attr('value');
	strData += '&t3_task=' + t3_task;
	strData += '&theme=' + t3_current_theme;

	url = 'index.php?q=admin/build/themes/settings/' + t3_current_theme;

	jQuery(ev.target).addClass('t3-loading');
	jQuery.ajax( {
		type : "POST",
		url : url,
		data : strData,
		success : function(respTxt) {
			respArr = Drupal.parseJson(respTxt);

			if (respArr['success']) {
				// add value to t3_layouts variable
				t3_layouts[respArr['name']] = {
					'name' : respArr['name'],
					'content' : respArr['content'],
					'type' : 'local'
				};
				t3_edit_layout_effect(respArr['name'], respArr['name'], 'add',
						ev.target);
				t3_display_message(respArr['message']);
			}
			jQuery(ev.target).removeClass('t3-loading');
			jQuery('#t3_layout_dialog_name').dialog('close');
		}
	});
}
function t3_edit_layout_effect(name, new_name, type, span) {
	var table = jQuery('table.jd-table-layout');
	var childs = table.find('tr');

	if (type == 'add') {
		var tr = jQuery('<tr></tr>');

		var number = childs.length + 1;
		var html = '<td class="jd-layout-num">' + number + '</td>';
		html += '<td>' + name + '</td>';
		html += '<td><span class="jd-edit" onclick="t3_edit_layout(\'' + name
				+ '\')">' + Drupal.t('Edit') + '</span>';
		html += '<span class="jd-clone" onclick="t3_layout_clone(\'' + name
				+ '\',this)">' + Drupal.t('Clone') + '</span>';
		html += '<span class="jd-delete" onclick="t3_layout_delete(\'' + name
				+ '\',this)">' + Drupal.t('Delete') + '</span>';
		html += '<span class="layout-type">' + Drupal.t('User Added')
				+ '</span></td>';

		tr.html(html);

		tr.appendTo(table);

		// need to change layout list at profile tab
		var layout_list = jQuery('#theme-profiles').find(
				'select[name=layout_desktop]');

		jQuery(layout_list).append(
				'<option value="' + new_name + '">' + new_name + '</option>');

		layout_list = jQuery('#theme-profiles').find(
				'select[name=layout_iphone]');

		jQuery(layout_list).append(
				'<option value="' + new_name + '">' + new_name + '</option>');

		layout_list = jQuery('#theme-profiles').find(
				'select[name=layout_handheld]');

		jQuery(layout_list).append(
				'<option value="' + new_name + '">' + new_name + '</option>');
	}

	if (type == 'delete') {

		var tr = jQuery(span).parent().parent();
		tr.remove();
		t3_layout_reorder_table();

		// remove from layout list in profile
		var layout_list = jQuery('#theme-profiles').find(
				'select[name=layout_desktop]');
		var current_layout = jQuery(layout_list).attr('value');
		if (current_layout == new_name) {
			jQuery(layout_list).attr('value', 'default');
		}
		var option = jQuery(layout_list).find('option[value=' + new_name + ']');

		jQuery(option).remove();

		layout_list = jQuery('#theme-profiles').find(
				'select[name=layout_handheld]');
		var current_layout = jQuery(layout_list).attr('value');
		if (current_layout == new_name) {
			jQuery(layout_list).attr('value', 'default');
		}
		option = jQuery(layout_list).find('option[value=' + new_name + ']');

		jQuery(option).remove();

		layout_list = jQuery('#theme-profiles').find(
				'select[name=layout_iphone]');

		var current_layout = jQuery(layout_list).attr('value');
		if (current_layout == new_name) {
			jQuery(layout_list).attr('value', 'default');
		}
		option = jQuery(layout_list).find('option[value=' + new_name + ']');

		jQuery(option).remove();
	}

	if (type == 'rename') {

		// here need to find tr with name like that
		childs.each(function(index, tr) {
			var tds = jQuery(tr).children();

			var td = tds[1];
			if (jQuery(td).text() == name) {
				jQuery(td).text(new_name);
				var spans = jQuery(tr).find('span');

				spans.each(function(index, span) {
					if (jQuery(span).hasClass('jd-edit')) {
						jQuery(span).unbind('click');
						jQuery(span).attr('onclick', '');
						jQuery(span).bind('click', function() {
							t3_edit_layout(new_name);
						});
					}

					if (jQuery(span).hasClass('jd-clone')) {
						jQuery(span).unbind('click');
						jQuery(span).attr('onclick', '');
						jQuery(span).bind('click', function() {

							t3_layout_clone(new_name);
						});
					}

					if (jQuery(span).hasClass('jd-delete')) {
						jQuery(span).unbind('click');
						jQuery(span).attr('onclick', '');
						jQuery(span).bind('click', function() {
							t3_layout_delete(new_name, this);
						});
					}
				});
			}
		});

		// set change of t3_layouts
		t3_layouts[new_name] = t3_layouts[name];

		t3_layouts[name] = undefined;
		t3_current_layout = new_name;
		// change from layout list of profile
		// remove from layout list in profile
		var layout_list = jQuery('#theme-profiles').find(
				'select[name=layout_desktop]');
		var option = jQuery(layout_list).find('option[value=' + name + ']');

		jQuery(option).text(new_name);
		jQuery(option).attr('value', name);

		layout_list = jQuery('#theme-profiles').find(
				'select[name=layout_handheld]');
		option = jQuery(layout_list).find('option[value=' + name + ']');

		jQuery(option).text(new_name);
		jQuery(option).attr('value', name);

		layout_list = jQuery('#theme-profiles').find(
				'select[name=layout_iphone]');
		option = jQuery(layout_list).find('option[value=' + name + ']');

		jQuery(option).text(new_name);
		jQuery(option).attr('value', name);
	}

	if (type == 'reset') {

		// here need to find tr with name like that
		childs.each(function(index, tr) {
			var tds = jQuery(tr).children();

			var td = tds[1];
			if (jQuery(td).text() == name) {

				var spans = jQuery(tr).find('span');
				spans.each(function(index, span) {
					if (jQuery(span).hasClass('reseting')) {
						jQuery(span).remove();
					}

					if (jQuery(span).hasClass('layout-type')) {
						jQuery(span).text(Drupal.t('core'));
					}
				});
			}
		});
	}

	if (type == 'override') {
		childs.each(function(index, tr) {
			var tds = jQuery(tr).children();

			var td = tds[1];
			if (jQuery(td).text() == name) {
				var spans = jQuery(tr).find('span');
				spans.each(function(index, span) {
					if (jQuery(span).hasClass('jd-reset')) {
						jQuery(span).remove();
					}

					if (jQuery(span).hasClass('layout-type')) {
						jQuery(span).text(Drupal.t('Modified'));
					}

					if (jQuery(span).hasClass('jd-clone')) {
						var reset = jQuery('<span onclick="t3_layout_reset(\''
								+ name + '\', this)" class="jd-reset">'
								+ Drupal.t('Reset') + '</span>')
						reset.insertAfter(jQuery(span));
					}
				});
			}
		});
	}
}

function t3_edit_layout(name) {
	jQuery('#t3_layout_content_edit')
			.attr('value', t3_layouts[name]['content']);
	jQuery('#t3_layout_name_edit').attr('value', name);
	jQuery('#t3_layout_name_value').attr('value', name);
	if (t3_layouts[name]['type'] == 'local') {
		jQuery('#t3_layout_name_edit').attr('disabled', false);
	} else {
		jQuery('#t3_layout_name_edit').attr('disabled', true);
	}
	jQuery('#t3_layout_dialog_edit').dialog("option", 'title',
			Drupal.t('Edit :') + name + Drupal.t(' layout'));
	jQuery('#t3_layout_dialog_edit').dialog("open");
	// finally set current layout variable
	t3_current_layout = name;
}

function t3_new_layout() {
	jQuery('#t3_layout_content_edit').attr('value', '');
	jQuery('#t3_layout_name_edit').attr('value', '');
	jQuery('#t3_layout_name_value').attr('value', '');
	jQuery('#t3_layout_name_edit').attr('disabled', false);
	jQuery('#t3_layout_dialog_edit').dialog("option", 'title',
			Drupal.t('New layout'));
	jQuery('#t3_layout_dialog_edit').dialog("open");
	t3_current_layout = '';
}

function t3_layout_reorder_table() {
	var table = jQuery('table.jd-table-layout');
	var txtNum = '';
	var tds = table.find('td.jd-layout-num');

	for (i = 0; i < tds.length; i++) {
		txtNum = i + 1;
		jQuery(tds[i]).text(txtNum);
	}
}
// ///////////////////////////////////////////////////
// /////////// FOR THEME FUNCTION ////////////////////
// ///////////////////////////////////////////////////
function t3_theme_init() {
	t3_init_upload_theme();
}

function t3_init_upload_theme() {
	var uploader = new qq.FileUploader(
			{
				element : document.getElementById('sub-theme-uploader'),
				action : 'index.php',
				params : {
					q : t3_q,
					t3_task : 'upload_theme',
					theme : t3_current_theme
				},
				// ex. ['jpg', 'jpeg', 'png', 'gif'] or []
				allowedExtensions : [ 'zip' ],
				// size limit in bytes, 0 - no limit
				// this option isn't supported in all browsers
				sizeLimit : 0,
				template : '<div class="qq-uploader">'
						+ '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>'
						+ '<div class="qq-upload-button">Upload & Install</div>'
						+ '<ul class="qq-upload-list" style="display:none"></ul>'
						+ '</div>',
				messages : {
					// serverError: "Some files were not uploaded, please
					// contact support and/or try again.",
					typeError : "{file} has invalid extension. Only {extensions} is allowed.",
					sizeError : "{file} is too large, maximum file size is {sizeLimit}.",
					emptyError : "{file} is empty, please select files again without it."
				},
				onSubmit : function(file, ext) {
					jQuery('#jd-theme-uploading').addClass('t3-loading');
					jQuery('#jd-theme-uploading').css('width', 10);
				},
				// Fired when file upload is completed
				// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
				// @param file basename of uploaded file
				// @param response server response
				onComplete : function(id, fileName, response) {
					if (response['theme_folder']) {
						t3_theme_add(response);
					}

					t3_display_message(response['message']);
					jQuery('#jd-theme-uploading').removeClass('t3-loading');
					jQuery('#jd-theme-uploading').css('width', 0);
				}
			});
}

function t3_theme_add(info) {
	var table = jQuery('#theme-themes > div >table.local-themes');

	var childs = table.find('tr');
	var tr = jQuery('<tr></tr>');

	var html = '';
	html += '<td>' + info['theme_folder'] + '</td>';
	html += '<td>' + info['version'] + '</td>';
	html += '<td>' + info['author'] + '</td>';

	var theme_action = '<span onclick="t3_theme_delete(\''
			+ info['theme_folder'] + '\',this)" class="jd-delete">'
			+ Drupal.t('Delete') + '</span>';
	html += '<td>' + theme_action + '</td>';

	tr.html(html);

	tr.appendTo(table);

	// apply to themes list in profile
	var selected_themes = jQuery('#selected-themes');
	var avail_themes = jQuery('#avail-themes');

	// add to edit sub-themes list
	var html = '';
	html += '<input type="checkbox" name="themes[]" value="'
			+ info['theme_folder'] + '" />';
	html += '<span>' + info['theme_folder'] + '</span>';
	var li = jQuery('<li></li>');
	li.html(html);

	li.appendTo(avail_themes);
	// add event
	var checkbox = li.find('input[type=checkbox]');

	jQuery(checkbox).change(
			function() {

				// If selected have not checked box, add to it

				if (jQuery(checkbox).attr('checked')) {

					var childs = selected_themes.find('li[id='
							+ jQuery(checkbox).attr('value') + ']');

					if (!childs.length) {

						var addItem = jQuery('<li id="'
								+ jQuery(checkbox).attr('value') + '">'
								+ jQuery(checkbox).attr('value') + '</li>');
						addItem.appendTo(jQuery('#selected-themes'));
					}
				} else {
					var childs = selected_themes.find('li[id='
							+ jQuery(checkbox).attr('value') + ']');
					jQuery(childs).remove();
				}

				var theme_hidden = t3_form.find('input[name=themes]');
				jQuery(theme_hidden).attr('value',
						jQuery('#selected-themes').sortable('toArray'));

				t3_profile_element_change(theme_hidden);
			});

}

function t3_theme_delete(name, span) {
	var u_profiles = [];
	for (pname in t3_profiles) {
		var used = false;

		if (t3_profiles[pname]['themes']) {
			var themes = t3_profiles[pname]['themes'];
			themes = themes.split(',');
			for (i = 0; i < themes.length; i++) {
				if (jQuery.trim(themes[i]) == jQuery.trim(name)) {
					u_profiles[u_profiles.length] = pname;
					break;
				}
			}

		}
	}

	if (u_profiles.length) {
		var msg = 'This theme can not be deleted because it is being used by profile(s):';
		for (i = 0; i < u_profiles.length; i++) {
			msg += u_profiles[i];
			if (u_profiles.length > i + 1)
				msg += ',';
		}
		msg += '. You can only delete the theme if it is not used by any profile.';
		alert(msg);
		return;
	}

	var del = confirm(Drupal.t('Are you sure you want to delete this theme:')
			+ name + ' ?');

	jQuery(span).addClass('t3-loading');
	if (del) {
		url = 'index.php?q=admin/build/themes/settings/' + t3_current_theme;

		jQuery.ajax( {
			type : "POST",
			url : url,
			data : 't3_task=delete_theme&name=' + name + '&theme='
					+ t3_current_theme,
			success : function(respTxt) {
				respArr = Drupal.parseJson(respTxt);
				if (respArr['success']) {
					var td = jQuery(span).parent();
					var tr = jQuery(td).parent();

					tr.remove();
					// apply to themes list in profile
					var selected_themes = jQuery('#selected-themes');
					var avail_themes = jQuery('#avail-themes');

					var sli = selected_themes.find('li[id=' + name + ']');
					jQuery(sli).remove();

					var ali = avail_themes.find('li > input[value=' + name
							+ ']');
					jQuery(ali).parent().remove();
				}

				t3_display_message(respArr['message']);
				jQuery(span).removeClass('t3-loading');
			}
		});
	}
}

function t3_theme_reset(name, span) {
	var reset = confirm(Drupal
			.t('Are you sure you want to reset this theme to default settings?'));

	jQuery(span).addClass('t3-loading');
	if (reset) {
		url = 'index.php?q=admin/build/themes/settings/' + t3_current_theme;

		jQuery.ajax( {
			type : "POST",
			url : url,
			data : 't3_task=delete_theme&name=' + name + '&theme='
					+ t3_current_theme,
			success : function(respTxt) {
				respArr = Drupal.parseJson(respTxt);
				if (respArr['success']) {
					var td = jQuery(span).parent();
					jQuery(span).remove();

					var info_span = jQuery('<span class="layout-type">'
							+ Drupal.t('core') + '</span>');
					info_span.appendTo(jQuery(td));
				} else {

				}
				jQuery(span).removeClass('t3-loading');
			}
		});
	}
}

// ////////////////////////////////////////////////////////////////////////////////
// /////////////////////////// SAVE ALL OF FUNCTION
// ///////////////////////////////
// ////////////////////////////////////////////////////////////////////////////////
jQuery(document).ready(function() {
	t3_init();

	t3_arrange_form();
	jQuery().mousemove(function(e) {
		window.mouseXPos = e.pageX;
		window.mouseYPos = e.pageY;
	});

	jQuery().click(function(e) {
		jQuery('.jd-click-dialog').hide();
	});

	jQuery('.show-when-click').click(function(event) {
		event.stopPropagation();
	});
})

function t3_arrange_form() {
	var fieldsets = jQuery('#system-theme-settings > div > fieldset');

	var global_fieldset = t3_form.find('fieldset#jd-global-setting');
	for (i = 0; i < 3; i++) {
		jQuery(fieldsets[i]).appendTo(jQuery(global_fieldset));
	}

	global_fieldset.prependTo(jQuery('#system-theme-settings > div'));
}

function t3_store() {
	var t3_data;

	var submit_button = jQuery('#system-theme-settings > div > input#edit-submit');

	jQuery(submit_button).attr('disabled', true);
	t3_data = {
		'profile' : t3_profiles,
		'general' : t3_general,
		't3_task' : 'store',
		'devmode' : jQuery('input[name=devmode]:checked').attr('value')
	};
	t3_data['var'] = jQuery(t3_form.find('input[name=var]')).attr('value');

	var strData = decodeURIComponent(t3_params(t3_data));

	url = 'index.php?q=admin/build/themes/settings/' + t3_current_theme;

	jQuery.ajax( {
		type : "POST",
		url : url,
		data : strData,
		success : function(respTxt) {
			var respArr = Drupal.parseJson(respTxt);

			if (respArr['success']) {
				t3_save = true;
				t3_form.submit();
			} else {
				t3_display_message(respArr['message']);
				jQuery(submit_button).attr('disabled', false);
			}

		}
	});
}

// ///////////////////////////////////////////////////////////////////////////////
// ////////////////////////////// BLOCK SUFFIX //////////////////////////////
// ///////////////////////////////////////////////////////////////////////////////
function t3_sblock_delete(id) {
	jQuery('tr#block-' + id).remove();
	var name = 'block[' + id + ']';
	// we also need to remove hidden field
	delete t3_profiles[t3_current_profile]['block'][id];
	jQuery('#block_item option').each(function() {
		if (jQuery(this).attr('value') == id) {
			jQuery(this).removeAttr('disabled');
			jQuery(this).attr('selected', 'selected');
			return false;
		}
		return true;

	});
	// t3_profiles[t3_current_profile]['block'].splice(id,1);
}

function t3_sblock_add() {
	if (jQuery('#block_item option:selected').attr('disabled')) {
		return;
	}
	var suffix = jQuery('#block_suffix').attr('value');

	var id = jQuery('#block_item option:selected').val();

	var title = jQuery('#block_item option:selected').text();

	if (suffix == '') {
		alert(Drupal.t('Please use suffix for this block'));
		return;
	}

	var tr = jQuery('<tr id="block-' + id + '"></tr>');
	var html = '<td class="block-name">' + title + '</td>';
	html += '<td>' + suffix + '</td>';
	html += '<td><span class="ja-delete" onclick="t3_sblock_delete(\'' + id
			+ '\')">Delete</span></td>';
	tr.html(html);

	// find table contain this
	tr.appendTo(jQuery('#block-class-suffix-table'));
	// we also need to add hidden field
	var hidden = jQuery('<input type="hidden" name="block[' + id + ']" value="'
			+ suffix + '" />');
	if (!t3_profiles[t3_current_profile]['block']) {
		t3_profiles[t3_current_profile]['block'] = {};
	}
	t3_profiles[t3_current_profile]['block'][id] = suffix;
	hidden.appendTo(tr);
	// remove this from selected
	jQuery('#block_item option:selected').attr("disabled", "disabled");
	jQuery('#block_item option').each(function() {
		if (!jQuery(this).attr('disabled')) {
			jQuery(this).attr('selected', 'selected');
			return false;
		}
		return true;

	});
	// jQuery('#block_item option:selected').attr("disabled")="disabled";
}
// ////////////////////////////////////////////////////////////////////////////////
// /////////////////////////// FIX FOR JQUERY 1.2
// /////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////////
function t3_params(a) {
	var traditional = false;
	var r20 = /%20/g;
	var s = [];

	// If an array was passed in, assume that it is an array of form elements.
	if (t3_isArray(a) || a.jquery) {
		// Serialize the form elements
		jQuery.each(a, function() {
			add(this.name, this.value);
		});

	} else {
		// If traditional, encode the "old" way (the way 1.3.2 or older
		// did it), otherwise encode params recursively.
		for ( var prefix in a) {
			buildParams(prefix, a[prefix]);
		}
	}

	// Return the resulting serialization
	return s.join("&").replace(r20, "+");

	function buildParams(prefix, obj) {
		if (t3_isArray(obj)) {
			// Serialize array item.
			jQuery.each(obj, function(i, v) {
				if (traditional || /\[\]jQuery/.test(prefix)) {
					// Treat each array item as a scalar.
					add(prefix, v);
				} else {
					// If array item is non-scalar (array or object), encode its
					// numeric index to resolve deserialization ambiguity
					// issues.
					// Note that rack (as of 1.0.0) can't currently deserialize
					// nested arrays properly, and attempting to do so may cause
					// a server error. Possible fixes are to modify rack's
					// deserialization algorithm or to provide an option or flag
					// to force array serialization to be shallow.
					buildParams(prefix + "["
							+ (typeof v === "object" || t3_isArray(v) ? i : "")
							+ "]", v);
				}
			});

		} else if (!traditional && obj != null && typeof obj === "object") {
			// Serialize object item.
			jQuery.each(obj, function(k, v) {
				buildParams(prefix + "[" + k + "]", v);
			});

		} else {
			// Serialize scalar item.
			add(prefix, obj);
		}
	}

	function add(key, value) {
		// If value is a function, invoke it and return its value
		value = jQuery.isFunction(value) ? value() : value;
		s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
	}
}

function t3_isArray(obj) {
	var toString = Object.prototype.toString;
	return toString.call(obj) === "[object Array]";
}

/**
 * return true if a = b
 * 
 * @param a
 * @param b
 * @returns
 */
function t3_compare_array(a, b) {
	if (!a && !b) {
		return true;
	} else if (!a && b || !b && a) {
		return false;
	}

	for (name in a) {
		if (!t3_isArray(a[name])) {
			if (!b[name])
				return false;
			if (a[name] != b[name])
				return false;
		} else {
			return t3_compare_array(a[name], b[name]);
		}
	}

	for (name in b) {
		if (!t3_isArray(b[name])) {
			if (!a[name])
				return false;
			if (b[name] != a[name])
				return false;
		} else {
			return t3_compare_array(b[name], a[name]);
		}
	}

	return true;
}

function cloneObject(source) {
	for (i in source) {
		if (typeof source[i] == 'source') {
			this[i] = new cloneObject(source[i]);
		} else {
			this[i] = source[i];
		}
	}
}

// confirm dialog
function t3_confirm_dialog(event, message) {

	if (!jQuery('#t3-confirm-dialog').attr('id')) {

		var t3_confirm_dialog = jQuery('<div id="t3-confirm-dialog"></div>');

		var html = '<div class="confirm">' + message + '</div>';
		t3_confirm_dialog.html(html);
		t3_confirm_dialog.dialog( {
			resizable : false,
			title : message,
			height : 140,
			modal : true,
			overlay : {
				opacity : 0.5,
				background : "black"
			},
			buttons : {
				'Confirm submit' : function() {

				},
				Cancel : function() {
					jQuery(this).dialog('close');
				}
			},
			autoOpen : false
		});
	}

	jQuery('#t3-confirm-dialog').dialog("open");
}

function t3_set_message(type, arrMsg) {

	var msg_class = '';
	switch (type) {
	case 'error':
		msg_class = 't3_error';
		break;
	case 'save':
		msg_class = 't3_save';
		break;
	default:
		break;
	}

	var html = '';
	html += '<ul class="' + msg_class + '">';
	if (t3_isArray(arrMsg)) {
		for (i = 0; i < arrMsg.length; i++) {
			html += '<li>' + arrMsg[i] + '</li>';
		}
	} else {
		html += '<li>' + arrMsg + '</li>';
	}
	html += '</ul>';

	jQuery('#t3-message').html(html);
	jQuery('#t3-message').show("slow");

	window.setTimeout(function() {
		// jQuery('#t3-message').animate({"opacity": "hide"}, 3000);
		jQuery('#t3-message').hide('slow');
	}, 5000);

}

function t3_display_message(message) {
	var html = '';
	for (type in message) {
		html += '<div class="messages ' + type + '">';
		html += '<ul>';
		for (i = 0; i < message[type].length; i++) {
			html += '<li>' + message[type][i] + '</li>';
		}
		html += '</ul>';
		html += '</div>';
	}

	jQuery('#t3-message').html(html);
	jQuery('#t3-message').show("slow");

	window.setTimeout(function() {
		// jQuery('#t3-message').animate({"opacity": "hide"}, 3000);
		jQuery('#t3-message').hide('slow');
	}, 5000);
}

function t3_display_message(message) {
	var html = '';
	for (type in message) {
		html += '<div class="messages ' + type + '">';
		html += '<ul>';
		for (i = 0; i < message[type].length; i++) {
			html += '<li>' + message[type][i] + '</li>';
		}
		html += '</ul>';
		html += '</div>';
	}

	jQuery('#t3-message').html(html);
	jQuery('#t3-message').show("slow");

	window.setTimeout(function() {
		// jQuery('#t3-message').animate({"opacity": "hide"}, 3000);
		jQuery('#t3-message').hide('slow');
	}, 5000);
}

function t3_tab_change(name) {
	var as = jQuery("div#jd-theme-setting  ul.primary  li  a");
	var href = "#theme-" + name;
	as.each(function(index, a) {
		if (href == jQuery(a).attr('href')) {
			jQuery(a).addClass('changed');
		}
	});
}

function t3_tab_nochange(name) {
	var as = jQuery("div#jd-theme-setting  ul.primary  li  a");
	var href = "#theme-" + name;
	as.each(function(index, a) {
		if (href == jQuery(a).attr('href')) {
			jQuery(a).removeClass('changed');
		}
	});
}

function t3_selectbox_set(val, default_val) {

}

function t3_final_filename(str) {
	str = str.replace(/[^a-zA-Z 0-9\-_]+/g, '');

	str = jQuery.trim(str);
	str = str.replace(/[\s]+/g, ' ');
	str = str.replace(/[\s]+/g, '-');
	str = str.replace('_', '-');

	return str;
}
